import huayiQDB.controller.huayiCollector as hyc
import huayiQDB.controller.huayiControl as hycc
import huayiQDB.controller.huayiUtils as hyu
import huayiQDB.controller.dbtools as db

def console_out(logFilename):
    ''''' Output log to file and console '''
    # Define a Handler and set a format which output to file
    logging.basicConfig(
        level=logging.DEBUG,  # 定义输出到文件的log级别，大于此级别的都被输出
        format='%(asctime)s  %(filename)s : %(levelname)s  %(message)s',  # 定义输出log的格式
        datefmt='%Y-%m-%d %A %H:%M:%S',  # 时间
        filename=logFilename,  # log文件名
        filemode='w')  # 写入模式“w”或“a”
    # Define a Handler and set a format which output to console
    console = logging.StreamHandler()  # 定义console handler
    console.setLevel(logging.INFO)  # 定义该handler级别
    formatter = logging.Formatter('%(asctime)s  %(filename)s : %(levelname)s  %(message)s')  # 定义该handler格式
    console.setFormatter(formatter)
    # Create an instance
    logging.getLogger().addHandler(console)  # 实例化添加handler

    # Print information              # 输出日志级别
    logging.debug('logger debug message')
    logging.info('logger info message')
    logging.warning('logger warning message')
    logging.error('logger error message')
    logging.critical('logger critical message')


if __name__ == "__main__":

    # with open("C:/Users/Administrator/huayiQDB/huayiQDB/files/nav.html", "r",encoding='utf-8') as f:
    #     for line in f.readlines():
    #         rst = re.sub('\n\s*\n', '\n', line)
    #         str.append(line)
    # str1 = "".join(str)
    str1 = "sd"
    test = ['                        <dl>                            <dt><span class="xin">关注度:<img src="../images/xin_2.gif" width="80"                                height="16" align="absmiddle" /></span><a style=" cursor:pointer" onclick="javascript:window.top.location.href=\'course.aspx?cid=79d10310-2a50-491f-8688-8bb5808e36a6&dept_id=a7e65008-e5c9-4390-ad23-a2cb00a69357\'" title="肾功能衰竭的病理生理学基础"><strong>                                        肾功能衰竭的病理生理学基础</strong></a></dt>                            <dd>                                <div class="txts">                                    国家I类 5.0学分                                                                        ', '                        <dl>                            <dt><span class="xin">关注度:<img src="../images/xin_2.gif" width="80"                                height="16" align="absmiddle" /></span><a style=" cursor:pointer" onclick="javascript:window.top.location.href=\'course.aspx?cid=caaf9b00-45e9-419d-83ff-eed6e4b11817&dept_id=a7e65008-e5c9-4390-ad23-a2cb00a69357\'" title="水、电解质代谢紊乱的病理生理基础"><strong>                                        水、电解质代谢紊乱的病理生理基础</strong></a></dt>                            <dd>                                <div class="txts">                                    国家I类 5.0学分                                                                        ', '                        <dl>                            <dt><span class="xin">关注度:<img src="../images/xin_2.gif" width="80"                                height="16" align="absmiddle" /></span><a style=" cursor:pointer" onclick="javascript:window.top.location.href=\'course.aspx?cid=d8f6f360-7764-47eb-9b2f-875c2cf21c8a&dept_id=a7e65008-e5c9-4390-ad23-a2cb00a69357\'" title="心血管功能活动与调控研究进展"><strong>                                        心血管功能活动与调控研究进展</strong></a></dt>                            <dd>                                <div class="txts">                                    国家I类 5.0学分                                                                        ', '                        <dl>                            <dt><span class="xin">关注度:<img src="../images/xin_2.gif" width="80"                                height="16" align="absmiddle" /></span><a style=" cursor:pointer" onclick="javascript:window.top.location.href=\'course.aspx?cid=30a201f0-3e52-4d68-adc8-438793941ab5&dept_id=a7e65008-e5c9-4390-ad23-a2cb00a69357\'" title="再生生物学的研究现状与进展"><strong>                                        再生生物学的研究现状与进展</strong></a></dt>                            <dd>                                <div class="txts">                                    国家I类 5.0学分                                                                        ', '                        <dl>                            <dt><span class="xin">关注度:<img src="../images/xin_2.gif" width="80"                                height="16" align="absmiddle" /></span><a style=" cursor:pointer" onclick="javascript:window.top.location.href=\'course.aspx?cid=c14837f1-c7b8-4d82-8585-25fdeaffe715&dept_id=a7e65008-e5c9-4390-ad23-a2cb00a69357\'" title="呼吸功能不全的病理生理学基础"><strong>                                        呼吸功能不全的病理生理学基础</strong></a></dt>                            <dd>                                <div class="txts">                                    国家I类 5.0学分                                                                        ', '                        <dl>                            <dt><span class="xin">关注度:<img src="../images/xin_2.gif" width="80"                                height="16" align="absmiddle" /></span><a style=" cursor:pointer" onclick="javascript:window.top.location.href=\'course.aspx?cid=de50506c-65fd-4f27-a55e-ae969979611b&dept_id=a7e65008-e5c9-4390-ad23-a2cb00a69357\'" title="糖代谢紊乱与疾病防治的病理生理学基础"><strong>                                        糖代谢紊乱与疾病防治的病理生理学基础</strong></a></dt>                            <dd>                                <div class="txts">                                    国家I类 5.0学分                                                                        ', '                        <dl>                            <dt><span class="xin">关注度:<img src="../images/xin_2.gif" width="80"                                height="16" align="absmiddle" /></span><a style=" cursor:pointer" onclick="javascript:window.top.location.href=\'course.aspx?cid=1c21e9d9-2b57-4d19-8512-c15be92b0d3f&dept_id=a7e65008-e5c9-4390-ad23-a2cb00a69357\'" title="心血管生理学与临床的基础研究进展"><strong>                                        心血管生理学与临床的基础研究进展</strong></a></dt>                            <dd>                                <div class="txts">                                    国家I类 5.0学分                                                                        ', '                        <dl>                            <dt><span class="xin">关注度:<img src="../images/xin_2.gif" width="80"                                height="16" align="absmiddle" /></span><a style=" cursor:pointer" onclick="javascript:window.top.location.href=\'course.aspx?cid=72531c19-dba7-42fa-bd17-c93faca63cba&dept_id=a7e65008-e5c9-4390-ad23-a2cb00a69357\'" title="肿瘤细胞的分子生物学研究与探讨"><strong>                                        肿瘤细胞的分子生物学研究与探讨</strong></a></dt>                            <dd>                                <div class="txts">                                    国家I类 5.0学分                                                                        ']
    with open("../files/nav.html", "r", encoding='utf-8') as f:
        pattern = ['<li class="menubox_01">(.*?)</ul></li>',  #0 menubox_01元素列表
                   '<a dept_id="(.*?)" class="menubox_03"',  #1 menubox_03的dept_id
                   'class="menubox_03"(.*?)</a>',  #2 为抽取menubox_03的title待加工
                   '[\u4e00-\u9fa5]',  #3 menubox_03的title
                   'onmouseout="aOnmouseOut\(this\)" onclick="reloadCourse\(this,\'(.*?)\'',  #4 menubox_03的reloadCourse_id
                   '<li class="listbox_01"><a dept_id="(.*?)"',  #5 listbox_01的dept_id
                   '<li class="listbox_01">(.*?)</li>',  #6 为抽取listbox_01的title待加工
                   'class="menubox_02"(.*)',  #7shua
                   '<a dept_id="(.*?)"'
                   ]

        pattern_lsit = [
            '<div class="item_r">(.*?)</dl>                        <br clear="all" />                    </div>                    <br clear="all" />',  # 筛选所需信息分组
            '<img src="../images/(.*?)\.gif',  # 关注度
            'javascript:window.top.location.href=\'(.*?)\'" title=',  # 课程链接
            'title="(.*?)"><strong>',  # 课程名字
            '<div class="txts">(.*?)</div>',  # 拆分四个<div class="txts">分组，第一个学分，第二个项目编号，第三个项目负责人，第四个单位
            '<span class="f12blue">(.*?)</span>',  # 在第二个分组中抽取，第二个项目编号.  在第三个分组抽取，第三个项目负责人
            'title=\'(.*?)\'>',  # 在第四个分组中抽取 单位
            '<span id="labAll">(.*?)</span>' #抽取课程的页数
        ]
        pattern_course_list=[
            '<div class="course">(.*?)</div>                            </div>',  #各学习分组
            '<span>{1}<a href=\'(.*?)\' target=',  #url
            '<strong>(.*?)</strong>', #学习名称
            '<div class="txts"(.*?)</div>', #老师、单位分组
            '<span class="f12blue">(.*?)</span>',  #授课老师、单位分别筛选
        ]

        pattern_Question = [
            '<tr align="left">(.*?)</td>		</tr>', #0筛出单个问题数组
            '<span id="gvQuestion_question_[0-9]">(.*?)</span>', #1筛出单个问题题目
            'id="gvQuestion_question_id_[0-9]" value="(.*?)"',  # 2筛出单个问题题目ID
            'id="gvQuestion_result_[0-9]" value="(.*?)"',  # 3筛出答案的value
            'name="gvQuestion\$ctl0[0-9]\$rbl" value="(.*?)"', #4筛出单个待选答案的value列表
            '<label for="gvQuestion_rbl_[0-9]_[0-9]_[0-9]">(.*?)</label>'  #5筛出单个待选答案的名字列表
        ]

        pattern_Nav = '//<!\[CDATA\[var cbItem=\{items:\[(.*?)\]\}//'  # 获取页面课程列表

        #text = f.read().replace('\r', '').replace('\n', '')
        #
        # print(hyccitem.deepAssembleUrlId(pattern, text))


        #stt = "".join(hyc.selectAllCourseFromNav(pattern_Nav, f.read())).encode('utf8')
        # strtable= []
        # lens = len(stt)
        # for char in stt:
        #     print(char)
        #     strtable.append(chr(char))
        # print(lens)

        #tt = "".join(hyc.selectAllCourseFromNav(pattern_Nav, f.read())).split(',')
        #cc = hyc.selectAllCourseFromNav(pattern_Nav, f.read())
        # import json
        pattern_2 = r'<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="(.*?)"'
        pattern_3 = r'id="__VIEWSTATEGENERATOR" value="(.*?)"'
        pattern_err = [
            '<h4>很抱歉，有(.*?)道题您答错了</h4>',
            '<dd title=\'(.*?)\'>',
            'value="重新学习" class="huise1" /><input name="" onclick="javascript: window\.location\.href = \'(.*?)\''
        ]
        #print(hyc.collect_ErrorExamResult(pattern_err, f.read()))

        import random


        #print(hyc.question_detail_AllList(f.read()))
        # import logging
        # import datetime
        # import logging.handlers
        #
        # log = logging.getLogger('debug_log')
        # log.setLevel(logging.DEBUG)
        # rf_handler = logging.handlers.TimedRotatingFileHandler('../log/all.log', when='midnight', interval=1, backupCount=7, atTime=datetime.time(0, 0, 0, 0))
        # rf_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
        # log.addHandler(rf_handler)
        # log.debug('debug message')

        import logging, logging.handlers
        import sys
        import huayiQDB.controller.log as log

        logs = log.logger
        # fmt = logging.Formatter("%(asctime)s - %(name)s - %(ip)s - %(username)s - %(message)s")
        # h_console = logging.StreamHandler(sys.stdout)
        # h_console.setFormatter(fmt)
        # logger = logging.getLogger("debug_log")
        # logger.setLevel(logging.DEBUG)
        # logger.addHandler(h_console)
        #
        # extra_dict = {"ip": "113.208.78.29", "username": "Petter"}
        # logger.debug("User Login!", extra=extra_dict)
        #
        # extra_dict = {"ip": "223.190.65.139", "username": "Jerry"}
        # logger.info("User Access!", extra=extra_dict)

        # logging.basicConfig(level=logging.INFO,
        #                     format='%(asctime)s [%(levelname)s] %(message)s (%(filename)s:L%(lineno)d)',
        #                     datefmt='%Y-%m-%d %H:%M:%S',
        #                     filename='../log/all.log',
        #                     filemode='a')
        #
        # logger = logging.getLogger("logs")
        #logs.info("info work  is running")


        # import pymysql
        #
        # conn = pymysql.connect(host="106.12.5.90", user="root", password="kkk@2286956", database="Qdb", charset="utf8")
        # cursor_test = conn.cursor()
        # sql = """insert into tmp_huayi_c (Q_Name, Q_IDValue, Q_ResultValue, A_Name, A_Value, Q_Tpye, Q_Study_Type) values('t','t','t','t','t','t','t')"""
        #
        # try:
        #     # 执行sql语句
        #     cursor_test.execute(sql)
        #     # 提交到数据库执行
        #     #data_result = cursor_test.fetchall()
        #     #print(data_result)
        #     conn.commit()
        # except:
        #     # 如果发生错误则回滚
        #     conn.rollback()
        #     #print("error")
        # # 关闭数据库连接
        # conn.close()


        # pattern_Nav = 'id="site_search1_hdnValue" value="\{\[(.*?)\]\}"'  # 获取页面课程列表
        # for one in hyc.selectAllCourseFromNav(pattern_Nav, f.read()):
        #     print(one['id'][4:-4])
        #str1 = str(hyc.selectAllCourseFromNav(pattern_Nav, f.read()))
        #list_1 = str1.split(",")
        #print(list_1)


    # def cookie_to_dict(cookie_list):
    #     cookie_dict = {}
    #     for one in cookie_list:
    #         real_name = one["name"]
    #         if cookie_dict.get(real_name) and cookie_dict.get(real_name) != one.get("value"):
    #             cookie_dict[real_name] = cookie_dict.get(real_name) + "," + one.get("value")
    #         else:
    #             cookie_dict[real_name] = one["value"]
    #     return cookie_dict
    #
    #
    # data = [{'domain': 'cme2.91huayi.com', 'httpOnly': True, 'name': 'ASP.NET_SessionId', 'path': '/', 'secure': False,
    #   'value': 'rgqgneb4mahrpi1vmaharznr'},
    #  {'domain': '.91huayi.com', 'httpOnly': False, 'name': 'Hm_lpvt_b8b19370771d6914b2aac73158a962b8', 'path': '/',
    #   'secure': False, 'value': '1604741240'},
    #  {'domain': '.91huayi.com', 'expiry': 1636277239, 'httpOnly': False,
    #   'name': 'Hm_lvt_b8b19370771d6914b2aac73158a962b8', 'path': '/', 'secure': False, 'value': '1604741240'},
    #  {'domain': '.91huayi.com', 'httpOnly': False, 'name': 'Hm_lpvt_ff0968fe442c4e89bf0c5108743a5f31', 'path': '/',
    #   'secure': False, 'value': '1604741239'},
    #  {'domain': '.91huayi.com', 'expiry': 1636277239, 'httpOnly': False,
    #   'name': 'Hm_lvt_ff0968fe442c4e89bf0c5108743a5f31', 'path': '/', 'secure': False, 'value': '1604741239'},
    #  {'domain': 'cme2.91huayi.com', 'httpOnly': False, 'name': 'userid', 'path': '/cme', 'secure': False,
    #   'value': 'ee68b7ab-fa51-4122-b4cb-ac4501035ec2'},{'domain': 'cme2.91huayi.com', 'httpOnly': True, 'name': 'ASP.NET_SessionId', 'path': '/', 'secure': False,
    #   'value': 'rgqgneb4mahrpi1vmaharznr'},{'domain': 'cme2.91huayi.com', 'httpOnly': True, 'name': 'ASP.NET_SessionId', 'path': '/', 'secure': False,
    #   'value': 'rgqgneb4mahrpi1vm'}]
    #
    # print(cookie_to_dict(data))

        # pattern = [
        #     '<div class="course">(.*?)</div>                            </div>',  # 各学习分组
        #     '<a id="ckjy" href="course_content\.aspx\?cwid=(.*?)"',  # url
        #     '<strong>(.*?)</strong>',  # 学习名称
        #     '<div class="txts"(.*?)</div>',  # 老师、单位分组
        #     '<span class="f12blue">(.*?)</span>',  # 授课老师、单位分别筛选
        #     '<img src=\'\.\.course_ware/images/(.*?)\''
        # ]
        #
        # #print(hyu.selectInfo(pattern[1], f.read()))
        # pattern_exam = '<form method="post" action="\.(.*?)"'
        # print(hyu.selectInfo(pattern_exam,f.read())[0])
    # cwid = hyu.getCWID('../course_ware/course_ware.aspx?cwid=90f9d59a-fdba-4e19-beab-ab3401190233')
    # print(cwid)
    #     pattern = [
    #         '<div class="search_condition">(.*?)</div>',
    #         '<dl>(.*?)</dl>',
    #         '<dd>(.*?)</dd>',  # 筛选出导航<a>分类
    #         'onclick=\'setUrlParam2\("(.*?)"\)\'>',  # 进一步筛选单个导航分类明细
    #         '>(.*?)</a>'
    #     ]
    #     print(hyc.nav_list(pattern, f.read()))

        # pattern_err = [
        #     '<h4>很抱歉，有(.*?)道题您答错了</h4>',
        #     '<dd title=\'(.*?)\'>',
        #     'value="重新学习" class="huise1" /><input name="" onclick="javascript: window\.location\.href = \'(.*?)\'',
        #     '<b style="float: left; margin-right: 0; margin-left: 20px;">(.*?)</b>'  # 获取 考试通过状态
        # ]
        #
        # print(str(hyu.selectInfo(pattern_err[3], f.read())[0]).strip())
        # 39f7bc56-60c4-4483-a74d-83b9187954af
        # e5029c54-b543-4ef2-828d-5fb0a06c6a96
        # dd036546-65e1-4412-93fe-bd3e6a5d42f3
        # db_sys = db.DBSystem()
        # db_sys.save_item('39f7bc56-60c4-4483-a74d-83b9187954af')
        # db_sys.save_study('e5029c54-b543-4ef2-828d-5fb0a06c6a96')
        # db_sys.save_course('dd036546-65e1-4412-93fe-bd3e6a5d42f3')
        #
        # # print(db_sys.isInItem('39f7bc56-60c4-4483-a74d-83b9187954af'))
        # # print(db_sys.isInCourse('dd036546-65e1-4412-93fe-bd3e6a5d42f3'))
        # # print(db_sys.isInStudy('e5029c54-b543-4ef2-828d-5fb0a06c6a96'))
        # # db_sys.save_item('39f7bc56-60c4-4483-a74d-83b9187954af')
        # # db_sys.save_study('e5029c54-b543-4ef2-828d-5fb0a06c6a96')
        # # db_sys.save_course('dd036546-65e1-4412-93fe-bd3e6a5d42f3')
        # print(db_sys.isInCourse('edfcea04-a625-4eda-8dbe-c52682979cd7'))
        # print(db_sys.isInCourse('7f5a0a8e-9920-4a47-96e5-bb40fed76003'))
        # print(db_sys.isInCourse('c128b254-75b8-470b-98be-62a7674aac4a'))
        #
        # db_sys.db_close()
        def ArrayToStr(list):
            nums = len(list)
            str_list = []
            if nums:
                for i, one in enumerate(list):
                    if i < nums-1:
                        str_list.append(str(one))
                        str_list.append(";")
                    else:
                        str_list.append(str(one))
            else:
                str_list.append("nums数量为零")
            return "".join(str_list)
        # pattern_Nav1 = 'id="site_search1_hdnValue" value="\{\[(.*?)\]\}"'  # 获取页面课程列表
        # print(hyc.selectAllCourseFromNav(pattern_Nav, f.read()))
        list_1 = ['A、司库奇尤', 'B、依那西普', 'C、英夫利昔', 'D、阿达木', 'E、古塞奇尤']
        print(ArrayToStr(list_1))
